package com.sina.finance.api.framework.service.impl;


import com.sina.finance.api.framework.response.ErrorResponse;
import com.sina.finance.api.framework.response.Response;
import com.sina.finance.api.framework.service.IAPIService;
import com.sina.finance.api.framework.service.IErrorResponseService;
import com.sina.finance.api.framework.utils.ParameterParser;
import com.sina.finance.api.framework.validator.BusinessException;
import com.sina.finance.api.framework.validator.ConditionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Map;

public abstract class AbstractAPIService implements IAPIService {
	private final static Logger logger = LoggerFactory.getLogger(AbstractAPIService.class);

	@Resource
	protected IErrorResponseService errorResponseService;

	@Override
	public Response doJob(Map<String, String[]> paramMap) {
		ParameterParser parameterParser = ParameterParser.createInstance(paramMap);
		Response response = null;
		try {
			response = doJob_(parameterParser);
		} catch (ConditionException e) {
			response = errorResponseService.getErrorResponse(e.getCode(), e.getMessage());
			logger.error("API条件校验错误", e);
		} catch (BusinessException e) {
			response = errorResponseService.getErrorResponse(e.getCode(), e.getOuterMsg());
			logger.error("API业务异常", e);
		} catch (RuntimeException e) {
			response = errorResponseService.getErrorResponse("S0", "系统内部错误");
			logger.error("API系统内部错误", e);
		}
		return response;
	}

	protected ErrorResponse getErrorResponse(String code, String msg) {
		return errorResponseService.getErrorResponse(code, msg);
	}

	protected abstract Response doJob_(ParameterParser paramMap);

}
